<?php
namespace common\models\userLevel;

use api\modules\v1\models\userLevel\UserLevel;
use common\models\Common;
use common\models\Functions;
use common\models\Status;
use common\models\user\User;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserLevelLog extends Common
{
    public $endDate = '';

    public static function tableName()
    {
        return '{{%user_level_log}}';
    }

    //获取用户
    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }


    /**
     * 级别变化
     * @param int $userId
     * @param int $type
     * @param int $levelId
     * @param int $month
     * @param string $mark
     * @throws Exception
     */
    public static function record(
        $userId = 0,
        $type = Status::LEVEL_CHANGE_TYPE_RECHARGE,
        $levelId = 0,
        $month = 0,
        $mark = ''
    ) {
        $userId = intval($userId);
        $type = intval($type);
        $levelId = intval($levelId);
        if (empty($userId) || empty($type)) {
            throw new Exception("参数错误");
        }

        if (!array_key_exists($type, Status::LEVEL_CHANGE_TYPE_MAP)) {
            throw new Exception('级别变化类型不存在');
        }

        $userData = User::getOneInfoById($userId);
        $levelInfo = UserLevel::getCacheByWhere();
        $levelInfo = ArrayHelper::index($levelInfo,'id');

        $expireTime = '';
        $updateUserData['level_id'] = $levelId;
        $updateUserData['level_expire_time'] = $expireTime;
        $updateUserData['is_level'] = Status::COMMON_RADIO_YES;
        switch ($type) {
            case Status::LEVEL_CHANGE_TYPE_RECHARGE:

                # 开通续费
                #1.相同等级改为覆盖
                $where = $andWhere = [];
                $where['after_change'] = $levelId;
                $where['status'] = Status::LEVEL_CHANGE_STATUS_NORMAL;
                $where['user_id'] = $userId;
                $sameLevelInfo = static::getOneByAndWhere($where,$andWhere);
                if ($sameLevelInfo) {
                    static::updateData(['status' => Status::LEVEL_CHANGE_STATUS_COVER],[
                        'id' => $sameLevelInfo['id'],
                    ]);
                }

                $oldExpireTime = $sameLevelInfo ? $sameLevelInfo['expire_time'] : date('Y-m-d H:i:s');
                $expireTime = date('Y-m-d H:i:s',strtotime("+{$month} months",strtotime($oldExpireTime)));

                #2.用户信息
                $updateUserData['level_expire_time'] = $expireTime;

                $mark = $sameLevelInfo ? "续费会员：{$levelInfo[$levelId]['name']},有效期到{$expireTime}" : "开通会员：{$levelInfo[$levelId]['name']},有效期到{$expireTime}";
                break;

            case Status::LEVEL_CHANGE_TYPE_UPDATE:
                # 升级
                #1.低的等级改为冻结,并且冻结时间是当前时间+购买的高等级月份
                $where = $andWhere = [];
                $where['status'] = Status::LEVEL_CHANGE_STATUS_NORMAL;
                $where['user_id'] = $userId;
                $andWhere[] = ['<','after_change',$levelId];
                $lowLevelInfo = static::getOneByAndWhere($where,$andWhere,'*','after_change DESC,id DESC');
                if ($lowLevelInfo) {
                    static::updateData([
                        'status' => Status::LEVEL_CHANGE_STATUS_FREEZE,
                        'expire_time' => date('Y-m-d H:i:s',strtotime("+{$month} months",strtotime($lowLevelInfo['expire_time']))),
                    ],[
                        'id' => $lowLevelInfo['id'],
                    ]);
                }

                $expireTime = date('Y-m-d H:i:s',strtotime("+{$month} months"));
                #2.用户信息
                $updateUserData['level_expire_time'] = $expireTime;
                $mark = "升级会员：{$levelInfo[$lowLevelInfo['after_change']]['name']} 升级为 {$levelInfo[$levelId]['name']},有效期到{$expireTime}";


                break;

            case Status::LEVEL_CHANGE_TYPE_EXPIRE:
                # 到期
                $isLevel = Status::COMMON_RADIO_NO;
                $expireTime = '';
                #1.当前等级改为过期
                static::updateData(['status' => Status::LEVEL_CHANGE_STATUS_EXPIRE],[
                    'after_change' => $levelId,
                    'status' => Status::LEVEL_CHANGE_STATUS_NORMAL,
                    'user_id' => $userId,
                ]);
                #2.查询是否有冻结的低等级信息
                # 如果有，低等级改为正常
                $where = $andWhere = [];
                $where['status'] = Status::LEVEL_CHANGE_STATUS_FREEZE;
                $where['user_id'] = $userId;
                $andWhere[] = ['<','after_change',$levelId];
                $lowFreezeLevelInfo = static::getOneByAndWhere($where,$andWhere,'*','after_change DESC');
                if ($lowFreezeLevelInfo) {
                    static::updateData(['status' => Status::LEVEL_CHANGE_STATUS_NORMAL],[
                        'id' => $lowFreezeLevelInfo['id'],
                    ]);
                    $expireTime = $lowFreezeLevelInfo['expire_time'];
                    $isLevel = Status::COMMON_RADIO_YES;
                }

                $levelId = $lowFreezeLevelInfo ? $lowFreezeLevelInfo['after_change'] : 1;
                #2.用户信息
                $updateUserData['level_expire_time'] = $expireTime;
                $updateUserData['is_level'] = $isLevel;
                $updateUserData['level_id'] = $levelId;
                $mark = "会员到期，自动降级为{$levelInfo[$updateUserData['level_id']]['name']}";
                break;
        }


        //成功
        $insertData["user_id"] = $userId;
        $insertData["type"] = $type;
        $insertData["before_change"] = $userData['level_id'];
        $insertData["after_change"] = $levelId;
        $insertData["create_time"] = date("Y-m-d H:i:s");
        $insertData["expire_time"] = $expireTime;
        $insertData["mark"] = $mark;
        $insertData["status"] = $type != Status::LEVEL_CHANGE_TYPE_EXPIRE ? Status::LEVEL_CHANGE_STATUS_NORMAL : Status::LEVEL_CHANGE_STATUS_EXPIRE;
        $res = static::insertData($insertData);
        if (!$res) {
            throw new Exception("系统错误,请联系管理员", 10004);
        }

        //更新用户信息
        $userWhere['id'] = $userId;
        $res = User::updateData($updateUserData, $userWhere);
        if ($res === false) {
            throw new Exception("用户级别更新失败", 10005);
        }
    }


    // 处理过期情况
    public function expireLog()
    {
        $dateTime = date('Y-m-d H:i:s');
//        $dateTime = date('2022-07-30 17:26:17');
        $where['status'] = Status::LEVEL_CHANGE_STATUS_NORMAL;
        $andWhere[] = ['<', 'expire_time', $dateTime];
        $expireList = static::getByAndWhere($where, $andWhere);
        if (!empty($expireList)) {
            foreach ($expireList as $value) {
                $this->_expire($value);
            }
        }
    }

    // 处理过期情况
    public function _expire($logInfo = []) {
        $trans = Yii::$app->getDb()->beginTransaction();
        try {
            static::record(
                $logInfo['user_id'],
                Status::LEVEL_CHANGE_TYPE_EXPIRE,
                $logInfo['after_change']
            );
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
        }
    }
}
